/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string')) {
			if ((/^[0-9]+$/.test(time))) {
				// support "1548221490638"
				time = parseInt(time)
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), '/')
			}
		}

		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}

// 扫一扫
export function scancode() {
	// #ifdef H5
	// 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
	if (navigator.mediaDevices === undefined) {
		navigator.mediaDevices = {};
	}

	// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia 
	// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
	if (navigator.mediaDevices.getUserMedia === undefined) {
		navigator.mediaDevices.getUserMedia = function(constraints) {

			// 首先，如果有getUserMedia的话，就获得它
			var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
			console.log('getUserMedia', getUserMedia)
			// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
			if (!getUserMedia) {
				return Promise.reject('浏览器不支持开启摄像头');
			}

			// 否则，为老的navigator.getUserMedia方法包裹一个Promise
			return new Promise(function(resolve, reject) {
				getUserMedia.call(navigator, constraints, resolve, reject);
			});
		}
	}

	var video = document.createElement("video");
	var canvasElement
	var canvas
	// Use facingMode: environment to attemt to get the front camera on phones
	navigator.mediaDevices.getUserMedia({
		video: {
			facingMode: {
				exact: "environment"
			}

		}
	}).then(function(stream) {
		canvasElement = document.createElement('canvas')
		canvasElement.style.width = '100%'
		canvasElement.style.height = '100%'
		canvasElement.style.position = 'fixed'
		canvasElement.style.zIndex = '999'
		canvasElement.style.top = '0'
		canvasElement.onclick = function() {
			video.srcObject.getTracks().forEach(track => {
				track.stop()
			})
			video.srcObject = null
			canvasElement.parentElement.removeChild(canvasElement)
		}
		canvas = canvasElement.getContext("2d");
		document.body.appendChild(canvasElement)
		video.srcObject = stream;
		video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
		video.play();
		requestAnimationFrame(tick);
	}).catch(err => {
		console.log(err)
		let res = err == '浏览器不支持开启摄像头' ? err : '摄像头开启失败，请检查摄像头是否可用'

		uni.showToast({
			icon: 'none',
			title: res
		})
	})

	function tick() {
		if (video.readyState === video.HAVE_ENOUGH_DATA) {
			// canvasElement.hidden = false;

			canvasElement.height = video.videoHeight;
			canvasElement.width = video.videoWidth;
			canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
			var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
			var code = jsQR(imageData.data, imageData.width, imageData.height, {
				inversionAttempts: "dontInvert",
			});
			if (code) {
				// code.data
				console.log('code', code)
				drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58", canvas);
				drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58", canvas);
				drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58", canvas);
				drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58", canvas);
				document.body.removeChild(canvasElement)
				video.srcObject.getTracks().forEach(track => {
					track.stop()
				})
				video.srcObject = null
				//  扫码成功后动作
				// source  调用来源
				// 1首页扫一扫  功能：扫码提币，扫描邀请二维码激活社区
				// 2未激活社区扫一扫 功能：扫描邀请人二维码激活社区
				// 3提币页面扫一扫 功能：自动填充扫描到的信息到提币地址
				// let code = {
				// 	data: 'http://ec2-52-80-59-195.cn-north-1.compute.amazonaws.com.cn:8087/mobile/#/pages/regist/regist?code=dsd33'
				// }

				// switch (+source) {
				// 	case 1:

				// 		break
				// 	case 2:

				// 		break
				// 	case 3:
				// 		uni.redirectTo({
				// 			url: `../raise/raise?addr=${code.data}`
				// 		})
				// 		console.log(source);
				// 		break
				// }
				// return code.data
				uni.redirectTo({
					url: `../raise/raise?addr=${code.data}`
				})
			}
		}
		requestAnimationFrame(tick);
	}
	// #endif
	// #ifndef H5
	uni.scanCode({
		success: function(res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			return res.result
		}
	})
	// #endif
}

// 获取当前链接中指定参数的值
export function GetUrlParam(paraName, webUrl) {
	let url = ''
	if (webUrl) {
		url = webUrl
	} else {
		url = document.location.toString();
	}

	let arrObj = url.split("?");
	if (arrObj.length > 1) {
		let arrPara = '';
		let arr = '';
		for (let k = 1; k < arrObj.length; k++) {
			arrPara = arrObj[k].split("&");
			arr = ''
			for (var i = 0; i < arrPara.length; i++) {
				arr = arrPara[i].split("=");
				if (arr != null && arr[0] == paraName) {
					return arr[1];
				}
			}
		}

		return "";
	} else {
		return "";
	}
}

// 计算倒计时
export function countDown(enddate, nowtime) {
	// var leftTime = enddate * 1000 - Date.parse(new Date()); //计算剩余的毫秒数
	var leftTime = enddate * 1000 - nowtime * 1000; //计算剩余的毫秒数
	if (leftTime <= 0) {
		return '00:00:00'
	}
	var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
	var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
	var minutes = parseInt(leftTime / 1000 / 60 % 60, 10); //计算剩余的分钟
	var seconds = parseInt(leftTime / 1000 % 60, 10); //计算剩余的秒数
	days = checkTime(days);
	hours = checkTime(hours);
	minutes = checkTime(minutes);
	seconds = checkTime(seconds);
	var dayhour = checkTime(days * 24 + parseInt(hours))
	return `${dayhour}:${minutes}:${seconds}`
}

// 时间补零
export function checkTime(i) {
	if (i < 10) {
		i = "0" + i
	}
	return i
}

// 复制
export function copyString(str) {
	// #ifndef H5
	uni.setClipboardData({
		data: str,
		success: () => {
			uni.showToast({
				icon: 'none',
				title: 'copied'
			})
		}
	})
	// #endif

	// #ifdef H5
	const el = document.createElement('textarea');
	el.value = str;
	el.setAttribute('readonly', '');
	el.style.position = 'absolute';
	el.style.left = '-9999px';
	document.body.appendChild(el);
	const selected =
		document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
	el.select();
	document.execCommand('copy');
	document.body.removeChild(el);
	if (selected) {
		document.getSelection().removeAllRanges();
		document.getSelection().addRange(selected);
	}
	uni.showToast({
		title: 'copied',
		icon: 'none'
	})
	// #endif
}

export function numberToCurrencyNo(value) {
	if (!value) return 0
	// 获取整数部分
	const intPart = Math.trunc(value)
	// 整数部分处理，增加,
	const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
	// 预定义小数部分
	let floatPart = ''
	// 将数值截取为小数部分和整数部分
	const valueArray = value.toString().split('.')
	if (valueArray.length === 2) { // 有小数部分
		floatPart = valueArray[1].toString() // 取得小数部分
		return intPartFormat + '.' + floatPart
	}
	return intPartFormat + floatPart
}

